package com.example.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pay.dto.PrepayRequest;
import com.example.pay.dto.PrepayResponse;
import com.example.pay.entity.*;
import com.example.pay.mapper.*;
import com.example.pay.service.channel.AlipayPayService;
import com.example.pay.service.channel.PointsPayService;
import com.example.pay.service.channel.WeChatPayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PayService {
    private final OrderService orderService;
    private final PaymentTransactionMapper transactionMapper;
    private final WeChatPayService weChatPayService;
    private final AlipayPayService alipayPayService;
    private final PointsPayService pointsPayService;
    private final MemberPackageItemMapper itemMapper;
    private final TUserMapper userMapper;;
    private final UserPointsMapper userPointsMapper;
    private final PointsConfigDetailMapper configDetailMapper;

    public PrepayResponse prepay(PrepayRequest req) {
        // 数据校验
        Map<String, Object> map = checkData(req);
        TUser tUser = (TUser) map.get("user");
        MemberPackageItem item = (MemberPackageItem) map.get("item");
        MemberOrder order = orderService.createOrder(
                req.getProductType(), req.getProductId(), req.getPurchaseType(),
                req.getUserId(), tUser.getDisplayName(), tUser.getMobile());
        PrepayResponse resp = new PrepayResponse();
        if (req.getPurchaseType() == 1 ||  req.getPurchaseType() == 2){
            PaymentTransaction tx = new PaymentTransaction();
            tx.setOrderCode(order.getOrderCode());
            tx.setChannel(order.getPurchaseType());
            tx.setAmount(order.getPayAmount());
            tx.setStatus(0);
            transactionMapper.insert(tx);
            try {
                if (order.getPurchaseType() == 1) {
                    resp = weChatPayService.prepay(order,item);
                } else if (order.getPurchaseType() == 2) {
                    resp = alipayPayService.prepay(order,item);
                }else {
                    throw new IllegalArgumentException("不支持的购买类型: " + order.getPurchaseType());
                }
                // 记录返回payload（预下单成功，不代表支付成功，状态仍为待支付）
                tx.setResponsePayload(resp.getPayload().toString());
                transactionMapper.updateById(tx);
                return resp;
            } catch (RuntimeException e) {
                // 渠道调用失败：标记交易失败并记录错误信息
                tx.setStatus(2);
                tx.setResponsePayload("ERROR: " + e.getMessage());
                transactionMapper.updateById(tx);
                throw e;
            }
        }else if (req.getPurchaseType() == 3){
            pointsPayService.prepay(order,item);
            // 积分支付，直接返回成功
            resp.setResult(true);
        }
        return resp;
    }

    private Map<String,Object> checkData(PrepayRequest req) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.select("id,_mobile,_display_name");
        wrapper.eq("_uid",req.getUserId());
        TUser tUser = userMapper.selectOne(wrapper);
        if (tUser == null){
            throw new RuntimeException("用户不存在");
        }

        MemberPackageItem memberPackageItem = new MemberPackageItem();
        // 积分套餐
        if ("10001".equals(req.getProductType())){
            PointsConfigDetail detail = configDetailMapper.selectById(req.getProductId());
            memberPackageItem.setItemDesc(detail.getDetailDesc());
            memberPackageItem.setCurrentPrice(detail.getCurrentPrice());
        }else {
            MemberPackageItem item = itemMapper.selectOne(new LambdaQueryWrapper<MemberPackageItem>().eq(MemberPackageItem::getItemId,req.getProductId()));
            if (item == null){
                throw new RuntimeException("商品信息不存在");
            }
            BeanUtils.copyProperties(item,memberPackageItem);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",tUser);
        map.put("item",memberPackageItem);
        // 判断当前积分是否足够
        if (req.getPurchaseType() != null && req.getPurchaseType() == 3){
            // 获取用户积分
            UserPoints userPoints = userPointsMapper.selectOne(new LambdaQueryWrapper<UserPoints>().eq(UserPoints::getUid, tUser.getUid()));
            if (userPoints != null && userPoints.getAvailablePoints() < memberPackageItem.getCurrentPrice().intValue()*10){
                throw new RuntimeException("用户积分不足，无法购买");
            }
        }
        return map;
    }
}
